package com.trg.flex.messages
{
	import com.trg.flex.frm.FormContainer;
	
	import flash.display.DisplayObject;
	
	import mx.containers.VBox;
	import mx.events.FlexEvent;

	[DefaultProperty("messages")]
	public class MessagePanel extends VBox
	{
		public function MessagePanel()
		{
			super();
			topContainer = this;
			topContainer.addEventListener(FlexEvent.ADD, addListener);
			visible = false;
			includeInLayout = false;
		}
		
		protected var formContainer:FormContainer;
		protected var topContainer:DisplayObject;
		protected var _messages:Array = [];
		
		public function addMessage(msg:Message):void {
			if (msg is Message) {
				_messages.push(msg);
				applyMessages();
			}
		}
		
		public function setMessage(msg:Message):void {
			if (msg == null)
				messages = null;
			else
				messages = [msg];
		}
		
		public function clearMessages():void {
			messages = null;
		}
		
		[ArrayElementType("com.trg.flex.messages.Message")]
		public function get messages():Array {
			if (_messages.length == 0) return [];
			return [].concat(_messages);
		}
		public function set messages(msgs:Array):void {
			_messages = [];
			if (msgs != null) {
				for each (var msg:* in msgs) {
					if (msg is Message) _messages.push(msg);
				}
			}
			applyMessages();
		}

		protected function applyMessages():void {
			removeAllChildren();
			for each (var msg:Message in _messages) {
				addChild(new MessageRenderer(msg));
			}
			visible = (_messages.length > 0);
			includeInLayout = (_messages.length > 0);
		}
		
		protected function addListener(event:FlexEvent):void {
			topContainer.removeEventListener(FlexEvent.ADD, addListener);
			
			while(true) {
				if (topContainer.parent is FormContainer) {
					formContainer = topContainer.parent as FormContainer;
					formContainer.addMessagePanel(this);
					break;
				} else if (topContainer.parent == null) {
					topContainer.addEventListener(FlexEvent.ADD, addListener);
					break;
				}
				topContainer = topContainer.parent;
			}
		}
	}
}